package com.orangelife.mobile.individual.activity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.confirmOrder.entity.PaidInfo;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.pay.interfaze.IPayCallBack;
import com.orangelife.mobile.pay.interfaze.IPayManage;
import com.orangelife.mobile.pay.biz.PayManageImpl;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.pay.biz.ThridPayKeyRequest;
import com.orangelife.mobile.pay.activity.PaidResultActivity;
import com.orangelife.mobile.util.ToastHelper;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseResp;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 充值方式
 */
public class BalanceRechargeMethodActivity extends ThridPayKeyRequest implements View.OnClickListener {
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.btnRecharge)
    Button btnRecharge;
    @Bind(R.id.rlAlipayPaidPrice)
    RelativeLayout rlAlipayPaidPrice;
    @Bind(R.id.rlWechatPaidPrice)
    RelativeLayout rlWechatPaidPrice;
    @Bind(R.id.ibChooseAlipay)
    ImageView ibChooseAlipay;
    @Bind(R.id.ibChooseWechat)
    ImageView ibChooseWechat;
    private Dialog dlgLoading;
    private String outtradeno;
    private IPayManage iPayManage;
    private boolean isAplipay, isWeChat;
    private static final int BALANCE_RECHARGE = 0;
    private Map<String, Object> map;
    private PaidInfo paidInfo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_balance_recharge_method);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        tvTitle.setText(getResources().getString(R.string.tv_recharge_method));
        paidInfo = new PaidInfo();
        rlAlipayPaidPrice.setOnClickListener(this);
        rlWechatPaidPrice.setOnClickListener(this);
    }

    public void recharge(View v) {
        dlgLoading = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dlgLoading.show();
        String url = Constant.URL_BALANCE_RECHARGE;
        map = new HashMap<>();
        map.put("money", getIntent().getExtras().getString("money"));
        map.put("merID", UserSp.getLoginID());
        JSONRequest.getInstance().sendRequest(JSONRequest.POST, url, map, handler, BALANCE_RECHARGE, HttpUtil.ACTION_JSON);
    }

    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        public void handleMessage(android.os.Message msg) {
            DialogHelper.closeDialog(dlgLoading);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(msg.obj.toString());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            ;
            Map<String, Object> map2 = JSONHelper.jsonToMap(
                    msg.obj.toString());
            switch (msg.what) {
                case BALANCE_RECHARGE:
                    if (map2 != null) {
                        map2 = (Map<String, Object>) map2.get("entity");
                        outtradeno = map2.get("outtradeno").toString();
                        getKeyFromServer();
                    }
                    break;
                case PaymentModule.APILAY_KEY:
                    //try {
                    callBack(jsonObject);
                    //} catch (JSONException e) {
                    //	e.printStackTrace();
                    //}
                    break;
                case PaymentModule.WECHAT_KEY:
                    getWeChatJson(msg);
                    break;
                case Constant.WHAT_TOKEN_EXPIRED:
                    isLogin(dlgLoading);
                    break;
                case Constant.WHAT_ERROR_HTTP:

                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @SuppressWarnings("deprecation")
    private void getKeyFromServer() {
        Map<String, Object> rootMap = new HashMap<String, Object>();
        initParams("钱包充值", outtradeno, map.get("money").toString());
        if (!isAplipay && !isWeChat) {
            Toast.makeText(this, "你还未选择支付方式", Toast.LENGTH_SHORT).show();
        } else if (isAplipay) {
            getNewApilayFromServer(handler);
        } else if (isWeChat) {
            getWeChatFromServer(handler);
        }

    }

    private void callBack(JSONObject jsonObject) {
        iPayManage = new PayManageImpl(new IPayCallBack() {
            @Override
            public void success() {
                Toast.makeText(BalanceRechargeMethodActivity.this, "充值成功",
                        Toast.LENGTH_SHORT).show();
                setPaidColor();
                setResult(RESULT_OK);
                skipResult(0);
                finish();
            }

            @Override
            public void handling() {
                Toast.makeText(BalanceRechargeMethodActivity.this, "支付结果确认中",
                        Toast.LENGTH_SHORT).show();
                skipResult(1);
            }

            @Override
            public void fail() {
                Toast.makeText(BalanceRechargeMethodActivity.this, "充值失败",
                        Toast.LENGTH_SHORT).show();
                skipResult(2);
            }
        });
        //iPayManage.setParameter(BalanceRechargeMethodActivity.this,jsonObject);
        iPayManage.newPay(this, jsonObject);
    }

    private void skipResult(int result) {
        final Intent intent = new Intent(BalanceRechargeMethodActivity.this, PaidResultActivity.class);
        intent.putExtra("btnText", getString(R.string.home_return));
        intent.putExtra("orderInfo", "橙子生活-钱包充值");
        intent.putExtra("totalPrice", String.valueOf(map.get("money")));
        intent.putExtra(PaymentModule.PAID_METHOD, PaymentModule.mode[9]);
        switch (result) {
            case 0:
                intent.putExtra("info", getString(R.string.paid_success));
                break;
            case 1:
                intent.putExtra("padding", getString(R.string.apliay_paiding));
                intent.putExtra("info", getString(R.string.order_paiding));
                intent.putExtra("isPaiding", true);
                intent.putExtra("btnText", getString(R.string.close));
                break;
            case 2:
                intent.putExtra("error", getString(R.string.apliay_paid_failue));
                intent.putExtra("btnText", getString(R.string.close));
                intent.putExtra("info", getString(R.string.paid_failue));
                intent.putExtra("isSuccess", false);
                break;
        }
        ExitApplication.getInstance().addMainActivity(BalanceRechargeMethodActivity.this);
        startActivity(intent);
    }

    /**
     * 设置支付完成后的支付按钮颜色
     */
    private void setPaidColor() {
        btnRecharge.setEnabled(false);
        btnRecharge.setBackgroundResource(R.drawable.shape_btn_gray);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rlAlipayPaidPrice:
                ibChooseAlipay.setBackgroundResource(R.drawable.icon_selected);
                ibChooseWechat.setBackgroundResource(R.drawable.icon_unselected);
                isAplipay = true;
                isWeChat = false;
                break;
            case R.id.rlWechatPaidPrice:
                ibChooseWechat.setBackgroundResource(R.drawable.icon_selected);
                ibChooseAlipay.setBackgroundResource(R.drawable.icon_unselected);
                isWeChat = true;
                isAplipay = false;
                break;
        }
    }

    @Override
    public void getResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            paidInfo.setBtnText(getString(R.string.home_return));
            paidInfo.setOrderInfo("钱包充值");
            paidInfo.setTotalPrice(Constant.RMB_FLAG + map.get("money").toString());
            if (resp.errCode == 0) {
                paidInfo.setType(PaymentModule.mode[9]);
                paidInfo.setPaidInfo(getString(R.string.paid_success));
                paidInfo.setIsSuccess(true);
            } else if (resp.errCode == -1 || resp.errCode == -2) {
                paidInfo.setPaidInfo(getString(R.string.paid_failue));
                paidInfo.setBtnText(getString(R.string.close));
                paidInfo.setIsSuccess(false);
            }
            putPaidInfo(paidInfo);
        }
    }
}
